<template>
  <div>
    <a-modal v-model:open="open" title="轮播图修改" width="50%" @ok="handleOk">
      <h3>标题</h3>
      <a-input-group compact>
        <a-input v-model:value="CarouselInfo.title" style="width: 50%" />
      </a-input-group>
      <h3>选择图片</h3>
      <a-form-item label="">
        <a-upload
          v-model:file-list="fileList"
          :headers="headers"
          action="/aPi/web/admin/common/upload"
          list-type="picture-card"
          :before-upload="beforeUpload"
          @preview="handlePreview"
          @change="handleChange"
        >
          <div v-if="fileList.length < 1">
            <loading-outlined v-if="loading"></loading-outlined>
            <PlusOutlined />
            <div style="margin-top: 8px">上传</div>
          </div>
        </a-upload>
        <a-modal
          :open="previewVisible"
          :title="previewTitle"
          :footer="null"
          @cancel="handleCancel"
        >
          <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
      </a-form-item>
      <h3>顺序</h3>
      <a-input-group compact>
        <a-input v-model:value="CarouselInfo.sortOrder" style="width: 25%" />
      </a-input-group>
      <h3>跳转链接</h3>
      <a-input-group compact>
        <a-input v-model:value="CarouselInfo.linkUrl" style="width: 50%" />
      </a-input-group>
      <br />
      <a-space wrap style="display: flex; justify-content: center">
        <a-button type="primary" block size="middle" @click="UpdateCarousel()">
          修改轮播图
        </a-button>
      </a-space>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import {
  adminQueryCarouselByIdService,
  adminUpdateCraouselService
} from '@/api/carouse'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import { useUserStore } from '@/stores'
import { message } from 'ant-design-vue'
//-----------更新轮播图-------------
const UpdateCarousel = async () => {
  if (!CarouselInfo.value.title) {
    message.error('请填写标题')
    return
  } else if (!CarouselInfo.value.imageUrl) {
    message.error('请上传图片')
    return
  } else if (!CarouselInfo.value.sortOrder) {
    message.error('请填写顺序')
    return
  } else if (!CarouselInfo.value.linkUrl) {
    message.error('请填写跳转链接')
    return
  }
  console.log(CarouselInfo.value)
  const res = await adminUpdateCraouselService(CarouselInfo.value)
  if (res.data.code === 1) {
    message.success('修改成功')
  } else {
    message.success('修改失败')
  }
}
//----------图片上传相关------------
const userStore = useUserStore()
const fileList = ref([])
const headers = {
  adminToken: userStore.token
}
const previewVisible = ref(false)
const previewImage = ref('')
const previewTitle = ref('')
const loading = ref(false)
const handleCancel = () => {
  previewVisible.value = false
  previewTitle.value = ''
}
const handlePreview = async (file) => {
  previewVisible.value = true
  previewTitle.value =
    file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
}
const handleChange = (info) => {
  if (info.file.status === 'uploading') {
    loading.value = true
    return
  }
  if (info.file.status === 'done') {
    loading.value = false
    message.success(`${info.file.name} 文件上传成功！`)
    CarouselInfo.value.imageUrl = info.file.response.data
    previewImage.value = info.file.response.data
  }
  if (info.file.status === 'error') {
    loading.value = false
    message.error('上传失败！')
  }
}
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('图片格式有误!')
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小必须小于2MB!')
  }
  return isJpgOrPng && isLt2M
}
const props = defineProps({
  inputId: {
    type: Number,
    required: true
  }
})
const open = ref(false)
const CarouselInfo = ref({
  title: '',
  sortOrder: '',
  linkUrl: '',
  imageUrl: ''
})

const showModal = () => {
  console.log(props.inputId)
  console.log(CarouselInfo)
  open.value = true
}
watch(
  () => props.inputId,
  (newId) => {
    getCarouselInfo(newId)
  }
)
const emit = defineEmits(['open-change'])
const handleOk = () => {
  open.value = false
  if (!open.value) {
    // 当模态框关闭时，发出事件
    emit('open-change', open.value)
  }
}
const getCarouselInfo = async (id) => {
  try {
    const response = await adminQueryCarouselByIdService(id)
    CarouselInfo.value = response.data.data
    console.log(CarouselInfo)
    if (CarouselInfo.value.imageUrl) {
      fileList.value = [
        {
          uid: '-1', // 唯一标识符，必须为字符串
          name: 'picture.png', // 文件名称
          status: 'done', // 文件状态，表示已经上传完成
          url: CarouselInfo.value.imageUrl // 文件地址
        }
      ]
    }
  } catch (error) {
    console.error('获取轮播图信息失败:', error)
  }
}
defineExpose({ showModal })
</script>

<style>
/* 确保选择框可见 */
.ant-select {
  visibility: visible;
  display: inline-block;
}
</style>
